

const ajax = options => {
  const {
    type = 'get',
    datatype = 'json',
    data = {},
    successCB,
    path,
  } = options;

  // 把数据对象变成字符串 a=11&b=22
  let params = '';
  for (let key in data){
    params += `${key}=${data[key]}&`;
  }
  // 去掉最后一个&
  params = params.substring(0 , params.length -1)

  const xhr = new XMLHttpRequest();


  // 判断数据请求的类型
  if(type.toLowerCase() === 'get'){
    xhr.open('get' , path + '?' + params , true);
    xhr.send();
  }else{
    xhr.open('post' , path , true);
    // 设置请求头
    xhr.setRequestHeader('Content-type' ,'application/x-www-form-urlencoded;charset=utf-8');
    xhr.send(params);
  }

  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4 && xhr.status == 200){
      let data = xhr.responseText;
      if(datatype === 'json'){
        data = JSON.parse(data);
      }
      successCB(data);
    }
  }


}